#include <stdlib.h>
#include <stdio.h> 
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <netinet/in.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>

#define MAXLINE 1024
#define SERVER_PORT 9991
void
err_sys(const char *fmt, ...);
static void
err_doit(int errnoflag, int level, const char *fmt, va_list ap);
void str_cli(FILE *fp,int sockfd);
ssize_t
readline(int fd, void *vptr, size_t maxlen);

int main(int argc,char **argv){
	int sockfd,n;
	char recvline[MAXLINE+1];
	struct sockaddr_in servaddr;
	
	if(argc != 2){
		fprintf(stderr,"usage:a.exe <Ipaddress>");
		exit(-1);
	}
	
	if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0){
		perror("socket error");
		exit(-1);
	}
	bzero(&servaddr,sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(SERVER_PORT);
	if(inet_pton(AF_INET,argv[1],&servaddr.sin_addr) <= 0){
		fprintf(stderr,"inet_pton error for %s",argv[1]);
		exit(-1);
	}
	if(connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr)) < 0){
		perror("connect error");
		exit(-1);
	}
	
	str_cli(stdin,sockfd);
		
	exit(0);
}

void str_cli(FILE *fp,int sockfd){
	char sendline[MAXLINE],recvline[MAXLINE];
	int n;
	while(fgets(sendline,MAXLINE,fp) != NULL){
		if(write(sockfd,sendline,strlen(sendline)) != strlen(sendline))
			err_sys("write error");
		if ( (n = readline(sockfd, recvline, MAXLINE)) == -1)
			err_sys("readline error");
		fputs(recvline,stdout);
	}
}


void
err_sys(const char *fmt, ...)
{
	va_list		ap;

	va_start(ap, fmt);
	err_doit(1, 0, fmt, ap);
	va_end(ap);
	exit(1);
}


static void
err_doit(int errnoflag, int level, const char *fmt, va_list ap)
{
	int		errno_save, n;
	char	buf[MAXLINE];

	errno_save = errno;		/* value caller might want printed */

	vsprintf(buf, fmt, ap);					/* this is not safe */

	n = strlen(buf);
	if (errnoflag)
		snprintf(buf+n, sizeof(buf)-n, ": %s", strerror(errno_save));
	strcat(buf, "\n");

	fflush(stdout);		/* in case stdout and stderr are the same */
	fputs(buf, stderr);
	fflush(stderr);	
	return;
}
ssize_t
readline(int fd, void *vptr, size_t maxlen)
{
	ssize_t	n, rc;
	char	c, *ptr;

	ptr = vptr;
	for (n = 1; n < maxlen; n++) {
		if ( (rc = read(fd, &c, 1)) == 1) {
			*ptr++ = c;
			if (c == '\n')
				break;
		} else if (rc == 0) {
			if (n == 1)
				return(0);	/* EOF, no data read */
			else
				break;		/* EOF, some data was read */
		} else
			return(-1);	/* error */
	}

	*ptr = 0;
	return(n);
}

